package com.campus_activity.campus_activity.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.campus_activity.campus_activity.common.R;
import com.campus_activity.campus_activity.constant.HttpStatus;
import com.campus_activity.campus_activity.exception.BusinessException;
import com.campus_activity.campus_activity.service.VerifyCodeService;
import com.campus_activity.campus_activity.utils.IdentifyingCodeUtils;
import com.campus_activity.campus_activity.utils.RedisCache;
import com.campus_activity.campus_activity.utils.VerifyUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class VerifyCodeServiceImpl implements VerifyCodeService {

    private final RedisCache redisCache;

    /**
     * 发送短信验证码
     *
     * @param phone
     * @return
     */
    @Override
    public boolean sendMessage(String phone) {
        //验证手机号是否合法
        boolean ifPhone = VerifyUtils.isPhone(phone);
        if(!ifPhone) {
            throw new BusinessException(HttpStatus.ERROR, "手机号不合法");
        }

        if (StringUtils.isNotEmpty(phone)) {

            //生成随机的6位验证码
            String code = IdentifyingCodeUtils.generateIdentifyingCode(6).toString();

            //将生成的验证码缓存到Redis中，有效期为5分钟
            redisCache.setCacheObject(phone, code, 5, TimeUnit.MINUTES);

            return true;
        }
        return false;
    }

    /**
     * 验证手机验证码
     * @param phone
     * @param code
     * @return
     */
    @Override
    public boolean confirmMsg(String phone, String code) {
        //从Redis中获取缓存的验证码
        String realCode = redisCache.getCacheObject(phone);

        //判断验证是否正确
        if (code != null && code.equals(realCode)) {
            return true;
        }else {
            return false;
        }
    }

}
